import { defineStore } from 'pinia'

import { getToken, setToken, removeToken} from '../utils/token-utils'
import { getLogin, getUserInfo } from '../api'

/* 存储用户信息的*/
export const useUserInfoStore = defineStore(
    'userInfo',
    {
        persist: true,
        state: ()=>({
            token: getToken(),
            nickName: '',
            uid: ''
        }),
        actions: {
            // 登录方法
            async login(loginForm){
                //发起登录请求，获取到token
                const ret = await getLogin(loginForm)
                const token = ret.token
                //得到的token保存到浏览器空间中
                setToken(token)
                //得到token赋给系统的token属性
                this.token = token
            },
            //通过token，查询相应的用户信息，并赋值给state的属性值
            async getInfo(){
                const ret = await getUserInfo()
                this.nickName = ret.loginUser.username
                this.uid = ret.loginUser.userId
            },
            //重置用户信息发
            initUserInfo(){
                removeToken(),
                this.token = '',
                this.nickName = '',
                this.uid = ''
            }
        }
    }
)